var cur_group_index = 0;

function IGO_PaintImages(group_index) {
  var g = data.image_groups[group_index];
  var table = document.createElement('table');

  for (var i = 0; i < g.length; ++i) {
    var list = data.images[g[i]];
    var path = list[0];
    var tr = document.createElement('tr');

    // The first td is the image itself
    var td = document.createElement('td');
    var div = document.createElement('div');
    if (list[1]) {  // Deleted
      div.setAttribute('class', 'wrapper');
    }

    var img = document.createElement('img');
    img.setAttribute('onclick', 'IGO_ReverseDeletionStatus(' + g[i] + ');');

    div.appendChild(img);
    td.appendChild(div);
    tr.appendChild(td);

    // The second td is the properties of the image
    td = document.createElement('td');
    img.onload = IGO_ImageBindOnLoad(img, IGO_ImageOnLoadCallback, td);
    img.src = path;
    tr.appendChild(td);

    // The third td is the perception hash code
    td = document.createElement('td');
    td.innerHTML = list[2];
    tr.appendChild(td);

    // The fourth td is the bitmap of the perception hash code
    td = document.createElement('td');
    td.appendChild(UTIL_GetBlackWhiteCanvasUsingULongStr(list[2]));
    tr.appendChild(td);

    table.appendChild(tr);
  }

  var d = document.getElementById('id_div_image_container');
  UTIL_RemoveAllChildren(d);
  d.appendChild(table);
}

function IGO_ImageBindOnLoad(img, handler, td) {
  return function() {
    handler(img, td);
  }
}

function IGO_ImageOnLoadCallback(img, td) {
  td.innerHTML = img.naturalWidth + " * " + img.naturalHeight;
}

function IGO_ReverseDeletionStatus(idx) {
  var s = data.images[idx][1];
  data.images[idx][1] = 1 - s;
  IGO_PaintImages(cur_group_index);
}

function IGO_PaintPrev() {
  --cur_group_index;
  if (cur_group_index == -1) {
    cur_group_index = 0;
  } else {
    IGO_PaintImages(cur_group_index);
  }
}

function IGO_PaintNext() {
  ++cur_group_index;
  if (cur_group_index == data.image_groups.length) {
    cur_group_index = data.image_groups.length - 1;
  } else {
    IGO_PaintImages(cur_group_index);
  }
}

function IGO_ShowDeleted() {
  var table = document.createElement('table');

  for (var i in data.images) {
    if (data.images[i][1]) {
      var tr = document.createElement('tr');
      var td = document.createElement('td');
      td.innerHTML = data.images[i][0];
      tr.appendChild(td);
      table.appendChild(tr);
    }
  }

  var d = document.getElementById('id_div_deleted_images');
  UTIL_RemoveAllChildren(d);
  d.appendChild(table);
}

function IGO_HandleKeyDown(){ 
  var event = document.all ? window.event : arguments[0]; 
  if (event.keyCode == 37) IGO_PaintPrev();
  if (event.keyCode == 39) IGO_PaintNext();
} 

function IGO_ImageGroupOperationInit() {
  IGO_PaintImages(0);
  document.onkeydown = IGO_HandleKeyDown; 
}
